/**
 * Highligh a field in error
 */
function highlightField(field) {
	$(field).focus();
	$(field).css("background-color", "LightSalmon");
}

/**
 * Unhighlight all fields
 */
function unHighlightFields() {
	$("input:not([readonly])").each(function(index) {
		$(this).css("background-color", "white");
	});
}

/**
 * Display an error message for the field
 */
function addError(object, inputName) {
	var labelText = $.trim(object.text().replace(" *", ""));
	$("#fieldName").html(labelText);
	$("#fieldError").html(
			$("#fieldError").html() + "<br />" + $("#errorData").html());
	$("#fieldError").show();
	highlightField($("#" + inputName));
}

/**
 * Check the password
 */
function checkPassword() {
	var errors = 0;
	if ($("#password").length > 0 && $("#passwordConfirm").length > 0) {
		// Check if the password is well confirmed
		if ($("#password").val() != $("#passwordConfirm").val()) {
			$("#errorPasswordMatch").show();
			highlightField($("#password"));
			highlightField($("#passwordConfirm"));
			errors++;
		}
		// Check the length
		if ($("#password").val().length < 6 && $("#password").val().length > 0) {
			$("#errorPasswordTooShort").show();
			highlightField($("#password"));
			highlightField($("#passwordConfirm"));
			errors++;
		}
	}
	return errors;
}

/**
 * Check mail format
 * @returns {Number}
 */
function checkMail() {
	var regexp = "^([0-9a-zA-Z]+([_.-]?[0-9a-zA-Z]+)*@[0-9a-zA-Z]+[0-9,a-z,A-Z,.,-]*(.){1}[a-zA-Z]{2,4})+$";
	if ($("#mail").length > 0) {
		if (!$("#mail").val().match(regexp)) {
			$("#errorMailRegex").show();
			highlightField($("#mail"));
			return 1;
		} else {
			return 0;
		}
	}
	return 0;
}

/**
 * Check the registration form
 */
function checkForm() {
	// Reinit fields error
	unHighlightFields();
	$("#fieldError").hide();
	$("#fieldError").html("");
	var errors = 0;
	// Check each mandatory fields
	errors = checkMandatoryFields();
	errors = errors + checkPassword();
	errors = errors + checkMail();
	if (errors) {
		return false;
	}
	return true;
}

/**
 * Check mandatory fields
 */
function checkMandatoryFields() {
	var errors = 0;
	$("#user_datas label.mandatory").each(function(index) {
		var inputName = $(this).attr("for");
		if ($("#" + inputName).length == 0) {
			if ($("input[name='" + inputName + "']:checked").size() == 0) {
				errors++;
				addError($(this), inputName);
			}
		} else if ($("#" + inputName).val() == "") {
			errors++;
			addError($(this), inputName);
		}
	});
	return errors;
}

/**
 * Manage error address
 */
function addressError() {
	$("#errorAddressUnknown").show();
	$('#lat').val('0');
	$('#lng').val('0');
	$.unblockUI({
		fadeOut : 200
	});
}

/**
 * Process an address
 * @param results the results
 */
function processAddress(results) {
	if (results.geometry.location_type == "ROOFTOP"
			|| results.geometry.location_type == "RANGE_INTERPOLATED") {
		$('#lat').val(results.geometry.location.lat());
		$('#lng').val(results.geometry.location.lng());
		if (checkForm()) {
			$.unblockUI({
				fadeOut : 200
			});
			$('.withAddress').submit();
		}
	} else {
		addressError();
	}
}

/**
 * Loading screen
 */
function waitForResult() {
	$("#loadingScreen").spin({
		lines : 13, // The number of lines to draw
		length : 30, // The length of each line
		width : 4, // The line thickness
		radius : 32, // The radius of the inner circle
		corners : 1, // Corner roundness (0..1)
		rotate : 0, // The rotation offset
		color : '#000', // #rgb or #rrggbb
		speed : 2.2, // Rounds per second
		trail : 100, // Afterglow percentage
		shadow : false, // Whether to render a shadow
		hwaccel : false, // Whether to use hardware acceleration
		className : 'spinner', // The CSS class to assign to the spinner
		zIndex : 2e9, // The z-index (defaults to 2000000000)
		top : 'auto', // Top position relative to parent in px
		left : 'auto' // Left position relative to parent in px
	});
	$.blockUI({
		message : $("#loadingScreen"),
		css : {
			border : '0px',
			backgroundColor : 'none',
			top : ($(window).height()) / 2 + 'px',
			left : ($(window).width()) / 2 + 'px',
			width : '128px'
		},
		overlayCSS : {
			backgroundColor : '#fff',
			opacity : 0.6
		}
	});
}

/**
 * Search for an address
 */
function searchAddress(address) {
	var geocoder = new google.maps.Geocoder();
	geocoder.geocode({
		'address' : address
	}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			processAddress(results[0]);
		} else {
			addressError();
		}
	});
}
